import 'dart:async';

import 'package:color_dart/color_dart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:im_flutter_sdk_example/components/a_button/index.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginBind extends StatefulWidget {
  LoginBind({Key key}) : super(key: key);

  _LoginMailState createState() => _LoginMailState();
}

class _LoginMailState extends State<LoginBind> {
  static Map email = {"value": null, "verify": true};
  static Map code = {"value": null, "verify": true};

  SharedPreferences prefs;

  /// 开始倒计时 时间
  int startTime;

  /// 当前倒计时 时间
  int countDownTime = 0;

  /// 总倒计时时长
  final int speed = 60;

  Timer _timer;

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () async {
      prefs = await SharedPreferences.getInstance();
      startTime = prefs.getInt('startTime');

      int nowTime = G.getTime();

      if (startTime != null && startTime > 0) {
        if (nowTime - startTime > 60) {
          prefs.remove('startTime');
        } else {
          countDown();
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  /// 获取验证码
  getEmailCode() async {
    try {
      var res = await G.req.verificationCode.getMailCode(mail: email['value']);

      if (res.data == null) return;

      G.toast('获取验证码成功');
      startTime = G.getTime();
      countDown();
    } catch (e) {
      G.toast('获取验证码失败');
    }
  }

  /// 倒计时
  countDown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      int nowTime = G.getTime();
      int result = speed - (nowTime - startTime);
      if (result < 0) {
        prefs.remove('startTime');
        _timer?.cancel();
      }

      setState(() {
        countDownTime = result;
      });
    });
  }

  /// 登录
  login() async {
    if (!email['verify'] || email['value'] == null) {
      return G.toast('输入邮箱有误');
    }
    if (!code['verify'] || code['value'] == null) {
      return G.toast('验证码不正确');
    }

    /// 登录前移除user， 不然登录会提示token错误
    prefs.remove('user');

  }

  getUserDetail(String token) async {
    var res = await G.req.user.detail();

    var data = res.data;

    Map json = data['data']['base'];
    json['token'] = token;

    G.user.init(json);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: customAppbar(context: context, borderBottom: false),
      body: Container(
        color: hex('#fff'),
        padding: EdgeInsets.only(left: 35, right: 35, top: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('绑定手机号',
                style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold)),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 9),
              child: Text('您的微信账号 XXX 通过验证',
                  style: TextStyle(fontSize: 15, color: rgba(51, 51, 51, 1))),
            ),
            Text('绑定手机号，可同步第三方账号与手机号信息。经纪人不会看的您的手机号',
                style: TextStyle(fontSize: 12, color: rgba(191, 191, 191, 1))),

            /// 输入邮箱
            Container(
              height: 55,
              margin: EdgeInsets.only(top: 20),
              decoration: BoxDecoration(border: G.borderBottom()),
              child: TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    counterText: "",
                    border: InputBorder.none,
                    hintText: '请输入手机号',
                    hintStyle: TextStyle(
                      color: rgba(163, 163, 163, 1),
                      fontSize: 16,
                    )),
                onChanged: (e) {
                  RegExp regExp = RegExp(
                      "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+");
                  setState(() {
                    email['value'] = e;
                    email['verify'] = regExp.hasMatch(e);
                  });
                },
              ),
            ),

            /// 验证码
            Container(
              height: 55,
              decoration: BoxDecoration(border: G.borderBottom()),
              child: Row(
                children: <Widget>[
                  Flexible(
                    child: TextField(
                      maxLength: 4,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                          counterText: '',
                          border: InputBorder.none,
                          hintText: '请输入证码',
                          hintStyle: TextStyle(
                            color: rgba(163, 163, 163, 1),
                            fontSize: 16,
                          )),
                      onChanged: (e) {
                        setState(() {
                          code['value'] = e;
                          code['verify'] = e.length == 4 ? true : false;
                        });
                      },
                    ),
                  ),
                  Container(
                    height: 25,
                    decoration: BoxDecoration(
                        border: Border(
                            left: BorderSide(color: rgba(242, 242, 242, 1)))),
                  ),
                  buildGetEmailCode()
                ],
              ),
            ),

            /// 确认
            Container(
              margin: EdgeInsets.only(top: 25),
              child: AButton.normal(
                  width: double.infinity,
                  child: Text('绑定手机号'),
                  color: hex('#fff'),
                  bgColor: rgba(42, 125, 250, 1),
                  borderColor: rgba(136, 175, 213, 1),
                  onPressed: () => G.pushNamed('/login_mail')),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取验证码
  Container buildGetEmailCode() {
    return Container(
      child: AButton.normal(
          child: Text(countDownTime <= 0
              ? "获取验证码"
              : countDownTime < 10
                  ? '0$countDownTime'
                  : '$countDownTime'),
          color: email['verify'] && email['value'] != null
              ? rgba(25, 109, 236, 1)
              : rgba(166, 166, 166, 1),
          onPressed: () {
            if (countDownTime > 0) return;
            getEmailCode();
          }),
    );
  }
}
